package com.czy.ekp.template;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.czy.ekp.gen.GeneratorFactory;
import com.czy.ekp.gen.ModuleVo;
import com.czy.ekp.gen.TemplateCodeGenerator;
import com.czy.ekp.util.FileUtils;
import com.czy.ekp.util.ResultMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;

@Slf4j
@Service
public class TemplateService {

    String root = System.getProperty("user.dir");


    public List<Map> listTemplateFiles(String path){
        List<Map> files = new ArrayList<>();
        if(path == null){
            path = "/";
        }
        try{
            File staticDir = new File(root + path);
//            System.out.println(staticDir.getAbsolutePath());
            for(File file : staticDir.listFiles()){
                Map item = new HashMap();
                item.put("name", file.getName());
                String itemPath = file.getPath();
                itemPath = StrUtil.removeAll(itemPath, root);
                itemPath = StrUtil.replace(itemPath, File.separator, "/");
                item.put("path", itemPath);
                item.put("isDir", file.isDirectory());
                files.add(item);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return files;
    }

    public ResultMap getFileContent(String filePath){
        File file = new File(root + filePath);
        if(file.exists() && file.isFile()){
            return ResultMap.success().setData(FileUtil.readString(file, Charset.forName("UTF-8")));
        }
        return ResultMap.failure("文件不存在");
    }

    public ResultMap updateTemplateFile(String filePath, String content){

        File file = FileUtil.writeString(content, root + filePath, Charset.forName("UTF-8"));
        if(file.exists() && file.isFile()){
            return ResultMap.success();
        }
        return ResultMap.failure("文件不存在");
    }



}
